// @author anonymous 一位不愿透露名字的大哥私聊发给我的
var unlock = function () {
    if (device.isScreenOn()) return
    device.wakeUp();
    sleep(1000);
    swipe(device.width * 0.6, device.height * 0.7, device.width * 0.6, device.height * 0.1, 300)
    sleep(1000);
}

var kill = function (packageName) {
    app.openAppSetting(packageName);
    text(app.getAppName(packageName)).waitFor();
    // 设置搜索控件超时
    var is_sure = text('强行停止').findOne(500) || textContains('stop').findOne(500);
    if (is_sure && is_sure.enabled()) {
        is_sure.click();
        var ok = text('确定').findOne(500) || text('OK').findOne(500);
        ok && ok.click()
        log(app.getAppName(packageName) + "应用已被关闭");
        sleep(1000);
        back();
    } else {
        log(app.getAppName(packageName) + "应用不能被正常关闭或不在后台运行");
        back();
    }
}
var launch = function (packageName) {
    app.launch(packageName)
}

var clickCenter = function (_id) {
    var view
    if (typeof _id === 'object') {
        view = _id
    } else {
        var view = selector().id(_id).findOne(500)
    }
    if (!view) return

    var b = view.bounds()
    click(b.centerX(), b.centerY());
}
var loop = function (check, retry, doWhile) {
    doWhile = doWhile === undefined ? true : doWhile
    var result
    while (true) {
        doWhile && retry && retry()
        result = check()
        if (result) return result
        !doWhile && retry && retry()
    }
}

var whenDisappears = function (selector, timeout) {
    var done
    var result

    var timer = setTimeout(() => {
        done = true
    }, timeout)

    while (!done) {
        if (!selector.exists()) {
            result = true
            break
        }
    }

    clearTimeout(timer)
    return result
}

auto.waitFor()

var packageName = 'com.jingdong.app.mall'

var reload = function () {
    kill(packageName)
    launch(packageName)
    sleep(3000)
}

var openTheNSActivity = function () {
    loop(() => text('浏览记录').findOne(1000), () => clickCenter(desc('我的').findOnce()))
    loop(() => {
        var anl = id('com.jd.lib.personal:id/anl').findOne()
        return anl && /\d+/.test(anl.text())
    })
    selector().className('android.support.v7.widget.RecyclerView').scrollForward()
    sleep(1000)
    clickCenter(text('全民炸年兽').findOne())
}

unlock()

log('如果京东无响应或者脚本有问题，强制关闭即可。')

threads.start(function () {
    while (true) {
        textMatches(/.*(跳过|继续|收下).*/).filter(function (item) { return item.clickable() }).findOne().click()
    }
});

reload()
openTheNSActivity()
loop(() => textContains('邀请好友助力').findOne(500), () => clickCenter(text('做任务拿爆竹').findOnce()))

var exclusions = ['邀请好友助力', '开启LBS定位', '逛年货节主会场',]
var reg = new RegExp(exclusions.join('|'))
var todo = []
textContains('次)').find().forEach((item) => !reg.test(item.text()) && todo.push(item))
var progressReg = /(\d{1,2})\/(\d{1,2})/
for (var item of todo) {
    log(item.text())
    var found = item.text().match(progressReg)
    if (!found) continue
    var [done, all] = [+found[1], +found[2]]
    var button = item.parent().findOne(selector().clickable())
    if (!button) continue
    for (; done < all; done++) {
        loop(() => {
            var result = whenDisappears(textContains('邀请好友助力'), 1000)
            sleep(500)
            return result
        }, () => button.click())
        loop(() => {
            var result = textContains('邀请好友助力').findOne(1000)
            if (result) textMatches(/.*(恭喜获得|这个任务做完).*/).findOne()
            return result
        }, () => back())
    }
}

sleep(1000)

reload()
openTheNSActivity()

loop(
    () => {
        var target = textContains('个爆竹可炸跑').findOnce()
        var current = selector().textMatches(/^\d+$/).filter(function (match) {
            return match.id() !== 'com.jingdong.app.mall:id/vb'
        }).findOnce()
        return target && current && parseInt(target.text().match(/\d+/)[0])
            > parseInt(current.text().match(/\d+/)[0])
    },
    () => clickCenter(selector().textMatches(/^\d+$/).filter(function (match) {
        return match.id() !== 'com.jingdong.app.mall:id/vb'
    }).findOnce())
    , false
)

toast('done')
exit()
